package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.enums.BIProductReformEnum;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormEntityAddDTO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.ProFormService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.ProErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.form.pojo.dto.FormAddBatchDTO;
import com.xbongbong.pro.form.pojo.vo.FormAddBatchVO;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2022/10/28 14:11
 */
@Service("proFormService")
public class ProFormServiceImpl implements ProFormService {

    private static final Logger LOG = LoggerFactory.getLogger(ProFormServiceImpl.class);
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    @Override
    public FormAddBatchVO addBatch(FormAddBatchDTO formAddBatchDTO) throws XbbException {
        FormAddBatchVO formAddBatchVO = new FormAddBatchVO();
        try {
            String corpid = formAddBatchDTO.getCorpid();
            List<PaasFormEntity> formList = new ArrayList<>();
            if(Objects.nonNull(formAddBatchDTO) && Objects.nonNull(formAddBatchDTO.getFormList())){
                for(FormEntityAddDTO formEntityAddDTO: formAddBatchDTO.getFormList()) {
                    //套餐判断
                    if (Objects.equals(formEntityAddDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())) {
                        Integer status = packageStatusHelp.getPackageStatus(formAddBatchDTO.getCorpid(), ValueAddedTypeEnum.CUSTOM_FORM_NUM, formAddBatchDTO.getFormList().size());
                        if(!Objects.equals(status, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(status, PackageStatusEnum.WARNING.getCode())){
                            throw new XbbException(ProErrorCodeEnum.API_ERROR_260014);
                        }
                    }
                    PaasFormEntity paasFormEntity = new PaasFormEntity();
                    BeanUtil.copyProperties(formEntityAddDTO, paasFormEntity);
                    paasFormEntity.setCoOpPerms(JSONObject.toJSONString(formEntityAddDTO.getCoOpPerms()));
                    paasFormEntity.setSummary(JSONObject.toJSONString(formEntityAddDTO.getSummaryEntity()));
                    paasFormEntity.setLabels(JSONObject.toJSONString(formEntityAddDTO.getLabels()));
                    paasFormEntity.setAssociationList(JSONObject.toJSONString(formEntityAddDTO.getAssociationList()));
                    paasFormEntity.setBusinessRules(formEntityAddDTO.getBusinessRules());
                    paasFormEntity.setSurcharge(JSONObject.toJSONString(formEntityAddDTO.getSurcharge()));
                    paasFormEntity.setCustomTitle(JSONObject.toJSONString(formEntityAddDTO.getCustomTitle()));
                    long now = DateUtil.getInt();
                    paasFormEntity.setCreatorId(formAddBatchDTO.getUserId());
                    paasFormEntity.setAddTime(now);
                    paasFormEntity.setUpdateTime(now);
                    paasFormEntity.setHidden(0);
                    paasFormEntity.setSort(0);
                    formList.add(paasFormEntity);
                }
            }
            if(!formList.isEmpty()){
                paasFormModel.insertBatch(formList);
                if (Objects.equals(formAddBatchDTO.getCompanyInit(), 0)) {
                    String userName = formAddBatchDTO.getLoginUserName();
                    String userId = formAddBatchDTO.getUserId();
                    String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_FORM), userName, "");
                    mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM, OperateTypeEnum.NEW, "", "", memo, formAddBatchDTO.getHttpHeader());
                }
            }
            //下面还需要产品子表单的插入操作，这边要根据枚举BIProductReformEnum中businessType去做一个过滤
            Set<Integer> allBusinessTypes = BIProductReformEnum.getAllBusinessTypes();
            List<PaasFormEntity> shouldCompareMainPaasFormList = new ArrayList<>();
            formList.forEach(paasFormEntity -> {
                if (allBusinessTypes.contains(paasFormEntity.getBusinessType())) {
                    shouldCompareMainPaasFormList.add(paasFormEntity);
                }
            });
            if (CollectionsUtil.isNotEmpty(shouldCompareMainPaasFormList)) {
                paasFormModel.insertSubProductFormList(shouldCompareMainPaasFormList, allBusinessTypes);
            }
            formAddBatchVO.setFormList(formList);
            String key = corpid + "_"+ ValueAddedTypeEnum.CUSTOM_FORM_NUM.getType();
            paasRedisHelper.removeValue(RedisPrefixConstant.VALUE_ADDED, key);
        }catch (Exception e){
            LOG.error("paasForm.addBatch添加表单设计信息出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formAddBatchVO;
    }



}
